// 发送短信验证码页面
import React, { useState } from 'react'
import NavBarCom1 from './NarBarCom1'
import { Input, Cell, Button, Toast } from 'react-vant';
// 发送验证码接口和验证验证码接口
import { doSend, doCheck } from '@/api/design';
import { useNavigate } from 'react-router-dom'
type Props = {}

export default function Step2({ }: Props) {
    const reg = /^\d{5}$/
    const [show1, setShow1] = useState(false)//短信验证码按钮能否点击
    let [time, setTime] = useState(10)//设置倒计时
    const [show2, setShow2] = useState(true)//下一步按钮能否点击
    const navigate = useNavigate()
    const [value, setValue] = useState('')  //输入框的值
    console.log('tel', localStorage.getItem('tel'));  //获取从注册页面存取到本地的电话号码
    // 点击发送验证码
    const send = () => {
        doSend({ tel: localStorage.getItem('tel') }).then((res) => {
            console.log('发送短信验证码2', res);
            if (res.data.code == '200') {
                // 倒计时10秒，按钮禁用
                const timer = setInterval(() => {
                    time--;
                    // console.log('time', time);  //9,8,7,6... 倒计时
                    setShow1(true)
                    if (time == 0) {
                        setShow1(false)
                        clearInterval(timer)
                        time = 10
                    }
                    setTime(time)  //真正修改时间
                }, 1000)
            }
        })
    }
    // 点击下一步，验证验证码
    const goNext = () => {
        // 验证短信验证码
        doCheck({ tel: localStorage.getItem('tel'), telcode: value }).then((res) => {
            console.log('验证短信验证码', res);
            if (res.data.code == '200') {
                // 验证成功 跳转到密码页面
                navigate('/design/step3')
            } else {
                // 验证失败 提示
                Toast({
                    type: 'fail',
                    message: '短信验证失败',
                    position: 'top',
                })
            }
        })
    }
    return (
        <div>
            <NavBarCom1>京东注册-短信</NavBarCom1>
            <Cell>
                <Input
                    name='telcode' //name是提交表单的标识符
                    placeholder="请输入短信验证码"
                    value={value}  //value就是当前输入的值
                    // setValue(value)是将输入框的值赋值，短信验证码正则校验，设置按钮能否点击下一步
                    onChange={(value) => { setValue(value); reg.test(value) ? setShow2(false) : setShow2(true) }}
                    // time !=0 ? `${time}秒后发送验证码` : `发送验证码`
                    suffix={<Button disabled={show1} size="small" type="danger" round onClick={send} >{time != 10 ? `${time}秒后发送验证码` : `发送验证码`}</Button>}
                />
            </Cell>
            <Button disabled={show2} round nativeType='submit' type='primary' block style={{ margin: '10px 10px 0' }} onClick={goNext}>下一步</Button>
        </div>
    )
}